package com.pkcargo.util.spider;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;

public abstract class WebClient {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    protected HttpClient client;
    protected String pre;
    protected String post;

    public WebClient(String host) {
        client = new HttpClient();
        client.getHostConfiguration().setHost(host, 80, "http");
    }

    public WebClient() {
        client = new HttpClient();
        client.getHostConfiguration().setHost("", 80, "http");
    }

    /**
     * 用来Quartz调用实现自动执行
     *
     * @throws IOException 默认
     */
    public abstract void spiderJob() throws Exception;

    public String login(String user, String userName, String password,
                        String userPassword, String url) throws Exception {
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        PostMethod post = new PostMethod(url);
        NameValuePair nuser = new NameValuePair(user, userName);
        NameValuePair npass = new NameValuePair(password, userPassword);

        return postToServer(new NameValuePair[]{nuser, npass}, post);

    }

    //post login msg to server
    public String postToServer(NameValuePair[] nameValuePairs, PostMethod post)
            throws Exception {
        String redicretURL = null;
        post.setRequestBody(nameValuePairs);

        client.executeMethod(post);
//        System.out.println(post.getResponseBodyAsString());
        post.releaseConnection();
        int statusCode = post.getStatusCode();

        if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY)
                || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
            Header header = post.getResponseHeader("location");
            if (header != null) {
                redicretURL = new String(header.getValue());
            }
        }
        return redicretURL;
    }

    //
    //get html stream
    //
    public InputStream getContentAsStream(String url) throws Exception {
        GetMethod get = new GetMethod(url);
        client.executeMethod(get);
        return get.getResponseBodyAsStream();
    }

    /**
     * 使用Http Get协议获取URL的源代码
     *
     * @param url 网页地址
     * @return 源代码
     * @throws IOException 默认定义Exception
     */
    public String getWebContent(String url) throws Exception {
        GetMethod get = new GetMethod(url);
        client.executeMethod(get);
        return get.getResponseBodyAsString();
    }

    public String getWebContentByCookie(String url) throws Exception {
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        GetMethod getMethod = new GetMethod(url);
        getMethod.setRequestHeader("Cookie"," _uid=7887398; _email=fishman_son%40hotmail.com; _kx=6f789b279f5d67b2895cc8beb52b62fe_7887398; _user=e0a217326d1c9020387a60107967b868_7887398_1242635803");
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        int statusCode = client.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: "
                    + getMethod.getStatusLine());
            return null;
        } else
            return getMethod.getResponseBodyAsString();
    }


}
